# Product routes
from flask import Blueprint, request, jsonify
from app.models.product import (
    get_products_by_category, get_all_products, 
    get_product_by_id, get_products_by_category
)
from app.utils.database import get_db_cursor

products_bp = Blueprint('products', __name__)

@products_bp.route('/products', methods=['GET'])
def get_all_products_api():
    """Get all products"""
    category = request.args.get('category')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    search = request.args.get('search', '')
    
    try:
        if category:
            products, total = get_products_by_category(category, page, per_page, search)
            for product in products:
                product['category'] = category
        else:
            products, total = get_all_products(page, per_page, search)
        
        return jsonify({
            'products': products,
            'total': total,
            'page': page,
            'per_page': per_page
        })
    except Exception as e:
        return jsonify({'error': f'Failed to get products: {str(e)}'}), 500

@products_bp.route('/products/<category>/<int:product_id>', methods=['GET'])
def get_product(category, product_id):
    """Get single product details"""
    try:
        product = get_product_by_id(category, product_id)
        if not product:
            return jsonify({'error': 'Product does not exist'}), 404
        
        product['category'] = category
        return jsonify({'product': product})
    except Exception as e:
        return jsonify({'error': f'Failed to get products: {str(e)}'}), 500

@products_bp.route('/products/categories', methods=['GET'])
def get_categories():
    """Get product category statistics"""
    conn, cursor = get_db_cursor()
    try:
        categories = {}
        category_info = {
            'seafood': {'name': 'Seafood', 'emoji': '🦐'},
            'vegetables': {'name': 'Vegetables', 'emoji': '🥬'},
            'meats': {'name': 'Meats', 'emoji': '🍖'},
            'fruits': {'name': 'Fruits', 'emoji': '🍎'}
        }
        
        for category, info in category_info.items():
            cursor.execute(f"SELECT COUNT(*) FROM {category}")
            count = cursor.fetchone()['count']
            categories[category] = {
                'name': info['name'],
                'count': count,
                'emoji': info['emoji']
            }
        
        return jsonify({'categories': categories})
    finally:
        cursor.close()
        conn.close()

@products_bp.route('/products/recommended', methods=['GET'])
def get_recommended_products():
    """Get recommended products"""
    limit = request.args.get('limit', 8, type=int)
    
    # Number of recommended products per category
    per_category = limit // 4
    if per_category == 0:
        per_category = 1
    
    # Randomly recommend products from each category
    recommended = []
    
    try:
        # Seafood recommendations
        seafood = get_products_by_category('seafood', 1, per_category)[0]
        for item in seafood:
            recommended.append({**item, 'category': 'seafood'})
        
        # Vegetable recommendations
        vegetables = get_products_by_category('vegetables', 1, per_category)[0]
        for item in vegetables:
            recommended.append({**item, 'category': 'vegetables'})
        
        # Meat recommendations
        meats = get_products_by_category('meats', 1, per_category)[0]
        for item in meats:
            recommended.append({**item, 'category': 'meats'})
        
        # Fruit recommendations
        fruits = get_products_by_category('fruits', 1, per_category)[0]
        for item in fruits:
            recommended.append({**item, 'category': 'fruits'})
        
        # If total is insufficient, randomly supplement with products from other categories
        if len(recommended) < limit:
            remaining = limit - len(recommended)
            # Randomly select some products to supplement
            all_products = []
            all_products.extend([(item, 'seafood') for item in get_products_by_category('seafood', 1, 100)[0]])
            all_products.extend([(item, 'vegetables') for item in get_products_by_category('vegetables', 1, 100)[0]])
            all_products.extend([(item, 'meats') for item in get_products_by_category('meats', 1, 100)[0]])
            all_products.extend([(item, 'fruits') for item in get_products_by_category('fruits', 1, 100)[0]])
            
            import random
            random.shuffle(all_products)
            
            for item, category in all_products[:remaining]:
                if not any(r['product_id'] == item['product_id'] and r['category'] == category for r in recommended):
                    recommended.append({**item, 'category': category})
        
        return jsonify({'recommended': recommended[:limit]})
        
    except Exception as e:
        return jsonify({'error': f'Failed to get recommended products: {str(e)}'}), 500

@products_bp.route('/products/search', methods=['GET'])
def search_products():
    """Search products"""
    query = request.args.get('q', '')
    category = request.args.get('category', '')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    
    if not query:
        return jsonify({'error': 'Please enter search keywords'}), 400
    
    try:
        if category:
            products, total = get_products_by_category(category, page, per_page, query)
            for product in products:
                product['category'] = category
        else:
            products, total = get_all_products(page, per_page, query)
        
        return jsonify({
            'products': products,
            'total': total,
            'page': page,
            'per_page': per_page,
            'query': query
        })
    except Exception as e:
        return jsonify({'error': f'Search failed: {str(e)}'}), 500
